$(document).ready(function() {

	function GroupDto(grpName) {
		
		this.name = grpName;
	}
	
	function PasswordDto(oldPw, newPw, repeatNewPw) {
		
		this.oldPassword = oldPw;
		this.newPassword = newPw;
		this.repeatNewPassword = repeatNewPw;
	}
	
	function PreferenceDto(preferenceName, preferenceType) {
		
		this.name = preferenceName;
	    this.contentType = preferenceType;	
	}
	
	function CategoryDto(categoryName, contentType) {
		
		this.categoryName = categoryName;
	    this.contentType = contentType;	
	}
	
	var homePageElements = ["div#contentDocumentBox", "div#accountBox"];
	var advancedSearchElements = ["div#advancedSearchBox", "div#backHome"];
	var groupPageElements = ["div#groupSearchBox", "div#ownGroupsBox", "div#backHome"];
	var groupSearchResultElements = ["div#groupSearchBox", "div#resultBox"];
	var contentSearchResultElements = ["div#contentDocumentBox", "div#resultBox", "div#backHome"];
	var showGroupElements = ["div#showGroupBox", "div#groupSearchBox"];
	var documentUploadElements = ["div#contentUploadBox", "div#backHome"];
	var newGroupElements = ["div#groupSearchBox", "div#createGroupBox"];
	var accountElements = ["div#accountSettingsBox", "div#backHome"];
	var preferenceElements = ["div#addPreferenceBox", "div#ownPreferencesBox", "div#backHome"];

	function restoreHome() {
		
		collapseAllInnerContent();
		collapseBox("div#backHome");
		$.each(homePageElements, function(index, value) {
			showBox(value);
		});
	}
	
	function collapseAllInnerContent() {
		$("div.innerContentBox").css("display", "none");
	}
	
	function collapseBox(box) {
		$(box).css("display", "none");
	}
	
	function showBox(box) {
		$(box).css("display", "block");
	}
	
	function hoverSimulation(box) {
		
		$(box).hover(function() {
			
			$(this).css("background-color", "#888888");
		}, function() {
			
			var bodyBgColor = $("body").css("background-color");
			$(this).css("background-color", bodyBgColor);
		});
	}
	
	function clickSimulation(box) {
		
		$(box).bind("mousedown touchstart", function(e) {
			
			$(this).css("background-color", "#BBBBBB");
		});
		
		$(box).bind("mouseup touchend touchcancel", function(e) {
			
			var bodyBgColor = $("body").css("background-color");
			$(this).css("background-color", bodyBgColor);
		});
		
	}
	
	function registerMenuButton(button, elementsToLoad) {
		
		$(button).click(function() {
	
			collapseAllInnerContent();
			$.each(elementsToLoad, function(index, value) {
				showBox(value);
			});
		});
	}
	
	function registerLogout() {
		
		$("div.linkBox#logout").click(function() {
			window.location.replace("logout");
		});
	}
	
	function registerBackHomeLink() {
		
		$("div#backHomeLinkBox").click(function() {
			
			restoreHome();
		});
	}
	
	function clearSearchResultBox() {
		
		$("div#resultBox > .resultLinkBox").remove();
	}
	
	function appendToSearchResultBox(htmlElements) {
		
		$.each(htmlElements, function(index, value) {
			$("div#resultBox").append(value);
		});
	}
	
	function fillSearchResultBox(htmlElements) {
		
		clearSearchResultBox();
		appendToSearchResultBox(htmlElements);
	}
	
	function showGroupOverviewPage() {

		$("div#memberShipBox > .resultLinkBox").remove();
		
		collapseAllInnerContent();
		
		$.each(groupPageElements, function(index, value) {
			showBox(value);
		});
		
		$.get("rest/access/users/groups", function(data, textStatus, jqXHR) {
			
			var resultBoxes = "div.resultLinkBox";
			
			$("div#memberShipBox").append(generateHtmlGroupResult(data));
			hoverSimulation(resultBoxes);
			clickSimulation(resultBoxes);
			registerGetButton(resultBoxes, "rest/access/groups", showGroupFunction);
		
		}).fail(function() {
			alert("Error.");
		});
	}
	
	function registerGroupOverview() {

		
		$("div#manageAndViewGrps").click(function() {
			
			showGroupOverviewPage();
		});
	}
	
	function generateHtmlGroupResult(jsonData) {
		
		var htmlElements = new Array();
		$.each(jsonData, function(index, value) {
			
			var element = $("<div></div>", {"class": "resultLinkBox"}).append($("<p></p>", {"class" : "linkText", text : value.name, linkIdentifier : value.name}));
			htmlElements.push(element);
		});
		
		return htmlElements;
	}
	
	function createGroupTable (jsonData, boxToAppendTo, isAdmin) {
		var table = $("<table></table>", {id : "showGroupTable"});
		
		var headerRow = $("<tr></tr>");
		headerRow.append($("<th></th>", {text : "Group Name:"}));
		headerRow.append($("<th></th>", {text : "Group Members:"}));
		
		table.append(headerRow);

		if(jsonData.users == null) {
			
			var row1 = $("<tr></tr>");
			var row2 = $("<tr></tr>");
			var row3 = $("<tr></tr>");
			
			row1.append($("<td></td>", {text : jsonData.name}));
			row1.append($("<td></td>"));
			row2.append($("<th></th>", {text : "Group Admin:"}));
			row2.append($("<td></td>"));
			row3.append($("<td></td>", {text : jsonData.grpAdmin}));
			row3.append($("<td></td>"));
			
			table.append(row1);
			table.append(row2);
			table.append(row3);
		} else {
			
			$.each(jsonData.users, function (index, value) {
				
				var row = $("<tr></tr>");
				
				if(index == 0) {
					row.append($("<td></td>", {text : jsonData.name}));
				} else if(index == 1) {
					row.append($("<th></th>", {text : "Group Admin:"}));
				} else if(index == 2) {
					row.append($("<td></td>", {text : jsonData.grpAdmin}));
				} else {
					row.append($("<td></td>"));
				}
				
				row.append($("<td></td>", {text : value}));

				table.append(row);
				
				if(jsonData.users.length == 1 && index == 0) {
					
					var row2 = $("<tr></tr>");
					var row3 = $("<tr></tr>");
					
					row2.append($("<th></th>", {text : "Group Admin:"}));
					row2.append($("<td></td>"));
					row3.append($("<td></td>", {text : jsonData.grpAdmin}));
					row3.append($("<td></td>"));
					table.append(row2);
					table.append(row3);
					
				}
				
				if (jsonData.users.length == 2 && index == 1) {
					
					var row3 = $("<tr></tr>");
					
					row3.append($("<td></td>", {text : jsonData.grpAdmin}));
					row3.append($("<td></td>"));
					table.append(row3);
				}
				
			});
		}
		
		$(boxToAppendTo).append(table);
		
		if(isAdmin) {
			
			var contentGroupingBox = $("<div></div>", {"class" : "contentGroupingBox", id : "showPendingUsers"});
			var contentDesc = $("<p></p>", {"class" : "contentDesc", text : "Pending Users:"});
			
			contentGroupingBox.append(contentDesc);
			
			$(boxToAppendTo).append(contentGroupingBox);
			
			$.each(jsonData.pendingUsers, function(index, value) {
				
				var linkBox = $("<div></div>", {"class" : "linkBox", id : "linkBox_" + value});
				var paragraph = $("<p></p>", {"class" : "linkText", text : value});
				var yes = $("<input></input>", {"class" : "pendingUserButton", id : "buttonYes_" + value, value : "Yes", type : "button"});
				var no = $("<input></input>", {"class" : "pendingUserButton", id : "buttonNo_" + value, value : "No", type : "button"});
				
				linkBox.append(paragraph);
				linkBox.append(yes);
				linkBox.append(no);
				contentGroupingBox.append(linkBox);
				
				$("input#buttonYes_" + value).click(function() {
					
					var answer = confirm("Do you want to add the user to your group?");
					if(answer) {
						
						$.ajax({
							url: "rest/access/groups/" + jsonData.name + "/accept/" + value,
							type : "PUT",
							success: function(data, textStatus, jqXHR) {
								
								showGroupFunction("rest/access/groups", jsonData.name, isAdmin);
							},
							error : function(data, textStatus, jqXHR) {
					
								alert("Error message:  " + textStatus);
							}
						});
					}
					
				});
				
				$("input#buttonNo_" + value).click(function() {
					
					var answer = confirm("Do you want to deny the user being member of your group?");
					if(answer) {
						
						$.ajax({
							url: "rest/access/groups/" + jsonData.name + "/removepending/" + value,
							type : "DELETE",
							success : function (data, textStatus, jqXHR) {
								showGroupFunction("rest/access/groups", jsonData.name, isAdmin);
							},
							error : function(data, textStatus, jqXHR) {
					
								alert("Error message:  " + textStatus);
							}
						});
					}
				});
			});

		}
	}
	
	function clearShowGroup(boxToClear) {
		
		$(boxToClear + " > table#showGroupTable").remove();
		$(boxToClear + " > div#showPendingUsers").remove();
	}
	
	function setLeaveJoinLink(url, identifier, isAdmin) {
		
		$("div#showGroupOptions").off("click");
		
		$.get(url + "/" + identifier + "/membership/", function(data, textStatus, jqXHR) {
			
			if(data.responseStatus == "success") {
				
				if(!isAdmin) {
					
					$("p#showGroupOptionsText").text("Leave Group");
					$("div#showGroupOptions").click(function() {
						
						$.ajax({
							url : url + "/" + identifier +"/removeparticipant/",
							type : "DELETE",
							success : function(data, textStatus, jqXHR) {
					
								alert(data.responseDesc);
								showGroupOverviewPage();
							},
							error : function(data, textStatus, jqXHR) {
					
								alert("Error message:  " + textStatus);
							}
						});
					});
				} else {
					
					$("p#showGroupOptionsText").text("Delete Group");
					$("div#showGroupOptions").click(function() {
						
						$.ajax({
							url : url + "/" + identifier,
							type : "DELETE",
							success : function(data, textStatus, jqXHR) {
					
								alert(data.responseDesc);
								showGroupOverviewPage();
							},
							error : function(data, textStatus, jqXHR) {
					
								alert("Error message:  " + textStatus);
							}
						});
					});						
				}
				
			} else {

				$("#showGroupOptionsText").text("Join Group");
				$("div#showGroupOptions").click(function() {
					
					$.ajax({

						url : url + "/" + identifier +"/newparticipant/",  
						type : "PUT",
						success : function(data, textStatus, jqXHR) {
				
							alert(data.responseDesc);
							showGroupOverviewPage();
						},
						error : function(data, textStatus, jqXHR) {
				
							alert("Error message:  " + textStatus);
						},
						contentType : "application/json"
					});
				});
			}
		}, "json").fail(function() {
			
			alert("Error.");
		});

	}
	
	function showGroupFunction(url, identifier) {
		
		$.get(url + "/" + identifier, function(data, textStatus, jqXHR) {
			
			collapseAllInnerContent();
			
			var isAdmin = false;
			
			$.ajax({
				
				url : url + "/" + identifier + "/isadmin/",
				type : "GET",
				success : function(data, textStatus, jqXHR) {
				
					if(data.responseStatus == "success") {
					
						isAdmin = true;
					}
				},
				error: function(data, textStatus, jqXHR) {
					
					alert("Error message: " + textStatus);
				},
				async : false
			});
				
			setLeaveJoinLink(url, identifier, isAdmin);
			
			$.each(showGroupElements, function(index, value) {
				showBox(value);
			});
			clearShowGroup("div#showGroupBox");
			createGroupTable(data, "div#showGroupBox", isAdmin);
			
			}, "json").fail(function() {
				
				alert("Error.");
		});
	}
	
	function registerGetButton(boxes, url, showFunction) {
		
		$(boxes).click(function() {

			var identifier = $(this).children("p").first().attr("linkIdentifier");

			showFunction(url, identifier);
		});
	}

	function loadGroupSearchResult(jsonData) {
		
		var resultBoxes = "div.resultLinkBox";
		
		fillSearchResultBox(generateHtmlGroupResult(jsonData));
		
		hoverSimulation(resultBoxes);
		clickSimulation(resultBoxes);
		registerGetButton(resultBoxes, "rest/access/groups", showGroupFunction);
	}
	
	function showGroupSearchResult(jsonData, textStatus, jqXHR) {
		
		
		collapseAllInnerContent();
		
		$.each(groupSearchResultElements, function(index, value) {
			showBox(value);
		});
		
		loadGroupSearchResult(jsonData);
	}
	
	function groupSearchSubmit() {
		
		var inputVal = $("div#groupSearchInputBox > form > input#groupSearchInputText").val();
		
		$.get("rest/access/groups/search/" + inputVal, function(data, textStatus, jqXHR) {
			
			$("div#groupSearchInputBox > form > input#groupSearchInputText").val("");
			showGroupSearchResult(data, textStatus, jqXHR);
		}, "json").fail(function() {
			
			alert("Error.");
		});
	}
	
	function registerGroupSearchGo() {
		
		$("div#groupGo").click(function() {
			
			groupSearchSubmit();
		});
		
		$("div#groupSearchInputBox > form").attr("action", "javascript:");
	}
	
	function createGroupSubmit() {
		
		var inputVal = $("div#createGroupInputBox > form > input#createGroupInputText").val();
		
		if(inputVal != "") {
		
			var grp = new GroupDto(inputVal);
			
			$.ajax({
				url : "rest/access/groups",
				type : "POST",
				data : JSON.stringify(grp),
				processData : false,
				success : function(data, textStatus, jqXHR) {
					
					$("div#createGroupInputBox > form > input#createGroupInputText").val("");
					showGroupFunction("rest/access/groups", inputVal);
				},
				error : function(data, textStatus, jqXHR) {
					
					alert("Error message:  " + textStatus);
				},
				contentType : "application/json"
			});
			
		} else {
			
			alert("Please specify a group name.");
		}
	
	}
	
	function registerCreateGroupGo() {
		
		$("div#createGroupGo").click(function() {
			
			createGroupSubmit();
		});
		
		$("div#createGroupInputBox > form").attr("action", "javascript:");
	}
	
	function showContentFunction(url, identifier) {
		
		document.location = url + "/" + identifier;
	}
	
	function generateHtmlContentResult(jsonData) {
		
		var htmlElements = new Array();
		$.each(jsonData, function(index, value) {
			
			var element = $("<div></div>", {"class": "resultLinkBox"}).append($("<p></p>", {"class" : "linkText", text : value.displayedFilename, linkIdentifier : value.id}));
			htmlElements.push(element);
		});
		
		return htmlElements;
	}
	
	function showContentSearchResult(jsonData, textStatus, jqXHR) {
		
		var resultBoxes = "div.resultLinkBox";
		collapseAllInnerContent();
		
		$.each(contentSearchResultElements, function(index, value) {
			showBox(value);
		});
		
		fillSearchResultBox(generateHtmlContentResult(jsonData));
		
		hoverSimulation(resultBoxes);
		clickSimulation(resultBoxes);
		registerGetButton(resultBoxes, "rest/access/content", showContentFunction);
		
	}
	
	function contentSearchSubmit() {
		
		var inputVal = $("div#contentSearchInputBox > form > input#contentSearchInputText").val();
		
		if(inputVal != null && inputVal != "") {
			
			$.get("rest/access/content/search/" + inputVal + "/filtered/false" + "/filterPrefs/false", function(data, textStatus, jqXHR) {

				$("div#contentSearchInputBox > form > input#contentSearchInputText").val("");
				showContentSearchResult(data, textStatus, jqXHR);
			}, "json").fail(function() {
				
				alert("Error.");
			});
			
			addElementToAutoCompleteList(inputVal);
		}
	}
	
	function registerContentSearchGo() {
		
		$("div#contentGo").click(function() {
			
			contentSearchSubmit();
		});
		
		$("div#contentSearchInputBox > form").attr("action", "javascript:");
	}
		
	function submitRegisterUser() {
		
		var username = $("div#registerUserInputBox > form > input#regUsername").val();
		var password = $("div#registerUserInputBox > form > input#regPassword").val();
		var repeatPassword = $("div#registerUserInputBox > form > input#regPasswordRepeat").val();

		if (password != "" && repeatPassword != "") {

			if (password == repeatPassword) {

				var pwUserDto = new PasswordDto(null, password, repeatPassword);
				
				$.ajax({
							url : "rest/access/users/register/"+ username,
							type : "POST",
							data : JSON.stringify(pwUserDto),
							processData : false,
							success : function(data,
									textStatus, jqXHR) {

								alert(data.responseDesc);
								window.location.replace("similaritySearchHome.jsp");
							},
							error : function(data, textStatus,
									jqXHR) {

								alert("Error message:  "
										+ textStatus);
							},
							contentType : "application/json"
						});
			} else {
				
				alert("The passwords have to match.");
			}
		
		} else {
			
			alert("Empty fields are not allowed.");
		}
	}

				
	function registerRegisterUser() {
		$("form#registerUserInputBox").attr("action", "javascript:");
		
		$("div#registerGo").click(function() {
		
			submitRegisterUser();
		});
	}	

	function fillOwnPreferences() {

		$.get("rest/access/preferences/user", function(data, textStatus, jqXHR) {
			
			$("div#selectOwnPreferences > div.checkBoxContainer").remove();
			
			var fillCheckBox = $("div#selectOwnPreferences");
			
			$.each(data, function(index, value) {
				
				var preferenceName= value.name;
				var preferenceType = value.contentType;
				var checkBoxContainter = $("<div></div>", {"class" : "checkBoxContainer"});
				
				checkBoxContainter.append($("<input />", {type : "checkbox", name : "preference",
					value : preferenceName + "(" + preferenceType + ")", contentType : preferenceType, preferenceName : preferenceName, checked : ""}));
				checkBoxContainter.append(preferenceName + "(" + preferenceType + ") <br />");
				
				fillCheckBox.append(checkBoxContainter);
			});
			
		}, "json").fail(function() {
			alert("Error.");
		});	
	

		
	}
	
	function registerShowOwnPreferences() {
		
		$("div#preferenceSettings").click(function() {
			
			fillOwnPreferences();
		});
		
	}
	
	function registerSelectPreferences() {
		$("form#registerUserInputBox").attr("action", "javascript:");
		
		$("div#selectPreferencesGo").click(function() {

			submitSelectPreferences();
		});
	}	
	
	function submitSelectPreferences() {
		
		$.each($("div.checkBoxContainer input[type='checkbox']:not(:checked)"), function(index, value) {	
				
				$.ajax({
					url : "rest/access/preferences/name/" + value.getAttribute("preferenceName") + "/conttype/" + value.getAttribute("contentType"),
					type : "DELETE",
					error : function(data, textStatus, jqXHR) {
						
						alert("Error message:  " + textStatus);
					},
					async : false,
					contentType : "application/json"
				});
			}
		);
		
		fillOwnPreferences();
		
	}
	
	function changePasswordSubmit() {
		
		function resetFields() {
			
			$("div#changePasswordInputBox > form > input#oldPasswordInputText").val("");
			$("div#changePasswordInputBox > form > input#changePasswordInputText").val("");
			$("div#changePasswordInputBox > form > input#repeatChangePasswordInputText").val("");
		}
		
		var oldPassword = $("div#changePasswordInputBox > form > input#oldPasswordInputText").val();
		var newPassword = $("div#changePasswordInputBox > form > input#changePasswordInputText").val();
		var repeatNewPassword = $("div#changePasswordInputBox > form > input#repeatChangePasswordInputText").val();
		
		if (oldPassword != "" && newPassword != "" && repeatNewPassword != "") {
			
			if(newPassword == repeatNewPassword) {
				
				var pwDto = new PasswordDto(oldPassword, newPassword, repeatNewPassword);
			
				$.ajax({
					url : "rest/access/users/password",
					type : "PUT",
					data : JSON.stringify(pwDto),
					processData : false,
					success : function(data, textStatus, jqXHR) {
						
						resetFields();
						alert(data.responseDesc);
					},
					error : function(data, textStatus, jqXHR) {
						
						resetFields();
						alert("Error message:  " + textStatus);
					},
					contentType : "application/json"
				});
				
			} else {
				
				alert("The new passwords have to match.");
			}

		} else {
			
			alert("Empty fields are not allowed.");
		}		
	}
	
	function registerChangePasswordGo() {
		
		$("div#changePasswordGo").click(function() {
			
			changePasswordSubmit();	
		});
		
		$("div#changePasswordInputBox > form").attr("action", "javascript:");
	
		
	}
	
	function submitUploadGo() {
		
		var chosenFile = $("input#fileUploadInput").get(0).files[0];
		var chosenFileName = $("input#fileUploadInput").get(0).value;
		var chosenCategoryName = $("div#addCategoryInputBox > form > input#addCategoryInputText").val();
		var catPattern = /[\w\s\d]+\(Music|Picture|Text\)/;
		var contDesc = $("input#addContentDescInputText").val();

		if(contDesc == "") {
			
			contDesc = "default";
		}
		
		var chosenContent = $("input[name='content']:checked").val();
		
		if (catPattern.test(chosenCategoryName)) {
			
			var strarray = chosenCategoryName.split("(");
			var category = strarray[0]; 
			var contentType = strarray[1].substring(0, strarray[1].length - 1);
			
			if (chosenContent == contentType) {
				if(chosenFileName.substring(0,12) == "C:\\fakepath\\") { 
					chosenFileName = chosenFileName.substring(12);
				}
						
				if(chosenFile != null) {
					
						$.ajax({
							url : "rest/access/content/filename/" + encodeURIComponent(chosenFileName) + "/contenttype/"+ contentType +
							"/categoryname/" + encodeURIComponent(category) + "/contentdesc/" + encodeURIComponent(contDesc),
							type : "POST",
							data : chosenFile,
							processData : false,
							success : function(data, textStatus, jqXHR) {
								
								$("input#fileUploadInput").get(0).value = "";
								$("div#addCategoryInputBox > form > input#addCategoryInputText").val("");
								$("input#addContentDescInputText").val("");
								$("input[name='content']:checked").prop("checked", false);
								
								$("div#uploadProgressContainer").text("");
								
								alert(data.responseDesc);
							},
							error : function(data, textStatus, jqXHR) {
								
								alert("Error message:  " + textStatus);
							},
							xhr : function(){
								
						        	var myCustomXhr = $.ajaxSettings.xhr();

						        	myCustomXhr.upload.onprogress = function (progressVal) {
									
										var progressRelative = Math.floor((progressVal.loaded / progressVal.total) * 100);
										$("div#uploadProgressContainer").html("Uploading Progess: " + progressRelative + "%");
						        	};
						        	
						        	return myCustomXhr;
						    },
							contentType : "application/octet-stream"
						});
					
					fileReader.readAsBinaryString(chosenFile);
					
				} else {
					
					alert("Please choose a file.");
				}
			} else {
				
				alert("Content types do not match.");
			}
		} else {
			
			alert("The chosen category is invalid.");
		}
	}
	
	function registerUploadGo() {
		
		$("div#uploadGo").click(function() {
			
			submitUploadGo();
		});
	}
	
	function registerAddPrefAutoComp() {
		
		$("form#addPreferenceForm").attr("action", "javascript:");
		
		$("input#addPreferenceInputText").autocomplete({
			source: function(request, response) {
				
				respData = null;
				
				$.ajax({
					url : "rest/access/preferences/search/" + request.term,
					type : "GET",
					success : function(data, textStatus, jqXHR) {
						
						list = new Array();
						$.each(data, function(index, value) {
							list.push({value : JSON.stringify(value), label : value.name + "(" + value.contentType + ")"});
						});
						respData = list;
					},
					error : function(data, textStatus, jqXHR) {
						
						alert("Error message:  " + textStatus);
						respData = [];
					},
					complete: function(jqXHR, textStatus) {
						
						if(respData == null) {
							respData = [];
						}
						response(respData);
					}
				});
			},
			select: function(event, ui) {
				
				event.preventDefault();
				$("input#addPreferenceInputText").autocomplete("close");
				$("input#addPreferenceInputText").val("");
				$.ajax({
					url : "rest/access/preferences/",
					data : ui.item.value,
					type : "PUT",
					process: false,
					success : function(data, textStatus, jqXHR) {
						fillOwnPreferences();
					},
					error : function(data, textStatus, jqXHR) {
						alert("Error message:  " + textStatus);
					},
					contentType : "application/json"
				});
			},
			focus: function( event, ui ) {
				
				event.preventDefault();
			}});
	}
	
	function registerAddCategoryAutoComp() {
		
		$("form#addCategoryForm").attr("action", "javascript:");
		
		$("input#addCategoryInputText").autocomplete({
			source: function(request, response) {
				
				respData = null;
				
				$.ajax({
					url : "rest/access/categories/search/" + request.term,
					type : "GET",
					success : function(data, textStatus, jqXHR) {
						
						list = new Array();
						$.each(data, function(index, value) {
							list.push({value : JSON.stringify(value), label : value.categoryName + "(" + value.contentType + ")"});
						});
						respData = list;
					},
					error : function(data, textStatus, jqXHR) {
						
						alert("Error message:  " + textStatus);
						respData = [];
					},
					complete: function(jqXHR, textStatus) {
						
						if(respData == null) {
							respData = [];
						}
						response(respData);
					}
				});
			},
			select: function(event, ui) {
				
				event.preventDefault();
				$("input#addCategoryInputText").autocomplete("close");
				$("input#addCategoryInputText").val(ui.item.label);
			},
			focus: function( event, ui ) {
				
				event.preventDefault();
			}});
	
	}
	
	function submitDeleteUser() {
		
		if(confirm("Do you really want to delete your account.")) {
		
			$.ajax({
				url : "rest/access/users/",
				type : "DELETE",
				success : function(data, textStatus, jqXHR) {
					alert(data.responseDesc);
					window.location.replace("similaritySearchHome.jsp");
				},
				error : function(data, textStatus, jqXHR) {
					alert("Error message:  " + textStatus);
				},
			});
		}
	}
	
	function registerDeleteUser() {
		
		$("div#deleteAccountGo").click(function() {
			
			submitDeleteUser();
		});
	}
	
	function registerPreferenceMenuButton() {
		
		function isContentAdmin() {
			
			var isAdmin = false;
			
			$.ajax({
				
				url : "rest/access/users/iscontentadmin",
				type : "GET",
				success : function(data, textStatus, jqXHR) {
					if(data.responseStatus == "success") {
						isAdmin = true;
					}
				},
				error: function(data, textStatus, jqXHR) {
					alert("Error message: " + textStatus);
				},
				async : false
			});
			
			return isAdmin;
		}
		
		registerMenuButton("div#preferenceSettings", preferenceElements);
		
		$("div#preferenceSettings").click(function() {
			
			if(isContentAdmin()) {
				showBox("div#addCategoriesAdminBox");
			}
		});
		
		$("div#createCategoryGo").click(function() {
			
			if(isContentAdmin()) {
				
				var catName = $("form#createCategoryForm input#createCategoryInputText").val();
				var contType = $("form#createCategoryForm input[name='contentType']:checked");
				
				if(catName != null && catName != "" && contType != null) {
					var catDto = new CategoryDto(catName, contType.val());
					$.ajax({
						url : "rest/access/categories",
						type : "POST",
						data : JSON.stringify(catDto),
						process : false,
						success : function(data, textStatus, jqXHR) {
							
							$("form#createCategoryForm input#createCategoryInputText").val("");
							$("form#createCategoryForm input[name='contentType']:checked").prop("checked", false);
							alert(data.responseDesc);
						},
						error : function(data, textStatus, jqXHR) {
							
							alert("Error message: " + textStatus);
						},
						contentType : "application/json"
					});
				} else {
					
					alert("All fields need to be specified.");
				}
			}
		});
	}
	
	function registerAdvancedSearch() {
		
		function advancedSearchAjax(reqUrl) {
			
			$.ajax({
				url : reqUrl,
				type : "GET",
				success : function(data, textStatus, jqXHR) {
					
					var resultBoxes = "div.resultLinkBox";
					
					showBox("div#resultBox");
					fillSearchResultBox(generateHtmlContentResult(data));
					
					hoverSimulation(resultBoxes);
					clickSimulation(resultBoxes);
					
					$("input#advancedSearchNameTagContentDescText").val("");
					$("input[name='advfilesearch']:checked").prop("checked", false);
					document.getElementById("checkBoxSearchContent").checked = false;
					document.getElementById("checkBoxSearchContentPrefs").checked = false;
			
					registerGetButton(resultBoxes, "rest/access/content", showContentFunction);
					
				},
				error : function(data, textStatus, jqXHR) {
					
					alert("Error message: " + textStatus);
				},
				dataType: "json"
			});
		}
		
		$("div#advancedGo").click(function() {
			
			var srchText = $("input#advancedSearchNameTagContentDescText").val();
			
			if(srchText != null && srchText != "") {
				
				var srchChoice = $("input[name='advfilesearch']:checked").val();
				var shouldFilter = document.getElementById("checkBoxSearchContent").checked;
				var shouldFilterPrefs = document.getElementById("checkBoxSearchContentPrefs").checked;
	
				if(srchChoice == "name") {
					
					advancedSearchAjax("rest/access/content/searchbyname/" + srchText + "/filtered/" + shouldFilter + "/filterPrefs/" + shouldFilterPrefs);
				} else if(srchChoice == "description") {
					
					advancedSearchAjax("rest/access/content/searchbydescription/" + srchText + "/filtered/" + shouldFilter + "/filterPrefs/" + shouldFilterPrefs);
				} else if(srchChoice == "category") {
					
					advancedSearchAjax("rest/access/content/searchbycategory/" + srchText + "/filtered/" + shouldFilter + "/filterPrefs/" + shouldFilterPrefs);
				} else {
					
					advancedSearchAjax("rest/access/content/search/" + srchText + "/filtered/" + shouldFilter + "/filterPrefs/" + shouldFilterPrefs);
				}
				
				addElementToAutoCompleteList(srchText);
			}
		});
	}
	
	function addElementToAutoCompleteList(element) {
		
		if(window.localStorage) {
			
			var curElement;
			var maxSize = 10;
			
			var list = [];
			var strList = localStorage.getItem("list");
			
			var isAlreadyInList = false;
			
			if(strList) {
			
				list = JSON.parse(strList);
			}
			
			$.each(list, function(index, value) {
				
				if(value.value == element) {
					
					isAlreadyInList = true;
				}
				
				return !isAlreadyInList;
			});
			
			if(!isAlreadyInList) {
				
				if(localStorage.getItem("curElement")) {
					 
					curElement = localStorage.getItem("curElement");
				} else {
					
					curElement = 0;
					localStorage.setItem("curElement", curElement);
				}
			
				if(list.length < maxSize) {
					
					list.push({value : element});
				} else {
					
					list[curElement] = {value : element};
					curElement = (curElement + 1) % maxSize;
					localStorage.setItem("curElement", curElement);
				}
				
				localStorage.setItem("list", JSON.stringify(list));
				
				$("datalist#autoComplList").append($("<option>", {value : element}));
			}
		}
	}
	
	function fillAutoCompleteList() {
		
		if(window.localStorage) {
			
			if(localStorage.getItem("list")) {
				
				var list = localStorage.getItem("list");
				
				$.each(JSON.parse(list), function(index, value) {
					
					$("datalist#autoComplList").append($("<option>", {value : value.value}));
				});
			}
		}
	}
	
	
	
	if($("datalist#autoComplList").length) {	
		fillAutoCompleteList();
	}	
	if($("div#ownPreferencesBox").length && $("div#preferenceSettings").length) {
		registerSelectPreferences();
	}
	if($("div#advancedSearchBox").length && $("div#advancedSearchLink").length) {
		registerMenuButton("div#advancedSearchLink", advancedSearchElements);
		registerAdvancedSearch();
	}
	if($("div#deleteAccountGo").length) {
		registerDeleteUser();
	}
	if($("div#ownPreferencesBox").length && $("div#preferenceSettings").length) {
		registerShowOwnPreferences();
	}
	if($("div#preferenceSettings").length) {
		registerPreferenceMenuButton();
	}
	if($("div#backHome").length) {
		restoreHome();
	}
	if($("div#contentDocumentBox").length) {
		registerContentSearchGo();
	}
	if($("div#groupSearchBox").length) {
		registerGroupSearchGo();
	}
	if($("div#createGroupBox").length) {
		registerCreateGroupGo();
	}
	if($("div.linkBox").length) {
		hoverSimulation("div.linkBox");
		clickSimulation("div.linkBox");
	}
	if($("div#manageAndViewGrps").length) {
		registerGroupOverview();
	}
	if($("div#docUpload").length) {
		registerMenuButton("div#docUpload", documentUploadElements);
	}
	if($("div#newGroupLinkBox").length) {
		registerMenuButton("div#newGroupLinkBox", newGroupElements);
	}
	if($("div#accountSettings").length) {
		registerChangePasswordGo();
		registerMenuButton("div#accountSettings", accountElements);
	}
	if($("div.linkBox#logout").length) {
		registerLogout();
	}
	if($("div#backHomeLinkBox").length) {
		registerBackHomeLink();
	}
	if($("div#uploadGo").length) {
		registerUploadGo();
	}
	if($("div#addPreferenceBox").length) {
		registerAddPrefAutoComp();
	}
	if($("div#contentUploadBox").length) {
		registerAddCategoryAutoComp();
	}
	
	if($("div#registerBox").length) {
		registerRegisterUser();
	}
});

